import collections

import numpy
import pandas

from absl import flags

import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt

from pandas.plotting import register_matplotlib_converters
register_matplotlib_converters()

from coin.pnl.sim_stat_plot import (plot_multidays,
                                                            plot_detail_plotonly,
                                                            plot_orderdf_plotonly)


def print_sim_stats(sim_stats):
  labels, params, sstats = zip(*sim_stats)

  rows = []
  for i, (label, param, sstat) in enumerate(sim_stats):
    if sstat is None:
      continue
    odict = collections.OrderedDict(label.get_name_items(param))
    odict.update(sstat['pnl_stat'])
    odict['i'] = i
    rows.append(odict)

  df = pandas.DataFrame(list(rows))
  df = df.loc[:, df.notnull().all()]
  if df.empty:
    print("sim result empty!!")
  else:
    groupkey = df.columns[0:(df.columns.tolist().index('trading_date'))].tolist()
    group_df = df.groupby(groupkey)
    print(df.to_string())
    dtypemap = df.dtypes.to_dict()
    meankeyset = set([
        'sharpe',
        'net_ret',
        'grs_ret',
        'fill_cnt_ratio',
        'fill_ratio',
        'taker_ratio',
        'maker_ratio',
        'taker_ret',
        'maker_ret'
    ])

    aggmethod = {
        key: ('mean' if key in meankeyset else
              'sum' if numpy.issubdtype(dtypemap[key], numpy.number) else 'first')
        for key in group_df.mean().columns
    }
    statdf = group_df.agg(aggmethod)
    del statdf['i']
    print(statdf.to_string())

    for groupval, subdf in group_df:
      subdf = subdf.assign(start_time=subdf['time_range'].apply(lambda x: float(x.split('-')[0])))
      plot_multidays(groupkey=groupkey,
                     groupval=groupval,
                     subdf=subdf,
                     sim_stats=sim_stats,
                     idxs=subdf['i'])

      nametuple = "__".join([str(key) for key in groupval])
      for postfix, plotfunc in [("_orderplot", plot_detail_plotonly),
                                ("_overview", plot_orderdf_plotonly)]:
        filepath = f"{flags.FLAGS.sim_root}/{nametuple}{postfix}.pdf"
        from matplotlib.backends.backend_pdf import PdfPages
        with PdfPages(filepath) as pdf:
          for i in subdf.sort_values(['trading_date', 'start_time'])['i']:
            plotfunc(nametuple, sstats[i])
            pdf.savefig()
            plt.close()
